package info.motteke.qjdbc;

import info.motteke.util.Properties;
import java.io.IOException;
import java.io.InputStream;

public class QuickJDBCProperties {

    private static final QuickJDBCProperties instance = new QuickJDBCProperties();

    private static final boolean loaded;

    public static final String DEFAULT_CONNECTION_NAME = "default_connection_name";

    private Properties prop = new Properties();

    static {
        loaded = init();
    }

    private static boolean init(){
        InputStream is;
        ClassLoader cl = QuickJDBCProperties.class.getClassLoader();
        is = cl.getResourceAsStream("qjdbc.xml");

        if(is != null && initFromXML(is)){
            return true;
        }

        is = cl.getResourceAsStream("qjdbc.properties");
        if(is != null && initFromPlainProperties(is)){
            return true;
        }
        return false;
    }

    private static boolean initFromXML(InputStream is){
        try{
            instance.prop.loadFromXML(is);
            return true;
        } catch (IOException e){
            return false;
        }
    }

    private static boolean initFromPlainProperties(InputStream is) {
        try{
            instance.prop.load(is);
            return true;
        } catch (IOException e){
            return false;
        }
    }

    public static QuickJDBCProperties getInstance(){
        return instance;
    }

    public static boolean isLoaded(){
        return loaded;
    }

    public String getDefaultConnectionName(){
        return prop.getProperty(DEFAULT_CONNECTION_NAME);
    }
}
